package com.biovr.backend.restcontroller;


import com.biovr.backend.domain.Apparatus;
import com.biovr.backend.domain.Expirement;
import com.biovr.backend.domain.Reagent;
import com.biovr.backend.repository.ApparatusRepository;
import com.biovr.backend.repository.ExpirementRepository;
import com.biovr.backend.repository.ReagentRepository;
import com.biovr.backend.utils.RestResponse;
import com.biovr.backend.service.ExpirementServiceImpl;
import com.biovr.backend.utils.ResponseFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by monodev on 2017/5/8.
 * Expirement RestController
 */
@Api(value = "/expirements",description = "实验API", consumes="application/json")
@RestController
@RequestMapping("/expirements")
public class  ExpirementRestController {
    @Autowired
    private ExpirementServiceImpl expirementService;
    @Autowired
    private ExpirementRepository expirementRepository;
    @Autowired
    private ApparatusRepository apparatusRepository;
    @Autowired
    private ReagentRepository reagentRepository;


    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @ApiOperation(value="获得所有实验列表",response = Expirement.class,responseContainer = "List")
    @GetMapping
    public  RestResponse<?> getAll(){
        List<Expirement> tarExpms = expirementRepository.findAll();
        return  ResponseFactory.createRestResponse(true,"", tarExpms);
    }
    /**
     * 查找所有实验
     * @return
     */

    @ApiOperation(value="获得sttaus=true实验列表",response = Expirement.class,responseContainer = "List")
    @GetMapping("/actived")
    public  RestResponse<?> getAllActived(){
        List<Expirement> tarExpms = expirementRepository.findByStatus(true);
        return  ResponseFactory.createRestResponse(true,"", tarExpms);
    }
    /**
     * 根据ID查找
     * @param id
     * @return
     */
    @ApiOperation(value="查找单个实验",response = Expirement.class)
    @ApiImplicitParam(name = "id", value = "实验id", required = true, dataType = "path")
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public RestResponse<Expirement> findExpm(@PathVariable String id){
        Expirement tarExpm = expirementRepository.findOne(id);
        return  ResponseFactory.createSuccessResult(tarExpm);
    }

    /**
     * 增加实验，返回新增的实验
     * @param request
     * @param expirement
     * @return
     */
    @ApiOperation(value="增加实验", notes="POST增加实验，返回增加后的实验",response = Expirement.class)
    @ApiImplicitParam(name = "expirement", value = "实验对象至少包括实验名称", required = true, dataType = "Expirement")
    @PostMapping
    public RestResponse<?> addExpirement(HttpServletRequest request,@RequestBody  Expirement expirement) throws  Exception{
        //检查名称
        if(null==expirement.getName()||expirement.getName().equals("")){
            return ResponseFactory.createRestResponse(false,"实验名称不能为空！",null);
        }

        if(expirementRepository.findByIndex(expirement.getIndex())!=null){
            return ResponseFactory.createRestResponse(false,"实验编号重复！",null);
        }
        Expirement addedExpm = expirementService.addExpirement(request,expirement);
        return addedExpm==null?
          ResponseFactory.createRestResponse(false,"无法添加实验",null)
          : ResponseFactory.createRestResponse(true,"添加实验成功",addedExpm);
    }

    /**
     * 修改实验
     * @param expirement
     * @return
     */
    @PutMapping
    public RestResponse<Expirement> updateExpiremnent(@RequestBody Expirement expirement) throws Exception{
        Expirement tarExpm;
        //检查名称
        if(null==expirement.getName()||expirement.getName().equals("")){
            return ResponseFactory.createRestResponse(false,"实验名称不能为空！",null);
        }
        //检查标准编号
        if(null!=expirement.getStdCode() &&""!=expirement.getStdCode()){
            tarExpm = expirementRepository.findByStdCode(expirement.getStdCode());
            if(tarExpm!=null&&!tarExpm.getId().equals(expirement.getId())){
                return ResponseFactory.createRestResponse(false,"实验标准编号重复！",null);
            }
        }
        //检查编号
        tarExpm = expirementRepository.findByIndex(expirement.getIndex());
        if(tarExpm!=null){
            if(!tarExpm.getId().equals(expirement.getId())){
                return ResponseFactory.createRestResponse(false,"实验编号重复！",null);
            }

        }
        SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
        expirement.setUpdateTime(sdf.format(new Date()));


        Expirement updatedExpm = expirementRepository.save(expirement);
        return ResponseFactory.createRestResponse(true,"修改实验成功",updatedExpm);
    }
    /**
     * 删除实验
     * @param id
     * @return
     */
    @ApiOperation(value="DELETE根据ID删除实验", notes="使用实验ID删除实验")
    @ApiImplicitParam(name = "id", value = "删除实验Id", required = true, dataType = "string",paramType = "path")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public RestResponse<?> deleteExpirement(@PathVariable String id) throws Exception{
       expirementService.deleteExpirement(id);
        return  ResponseFactory.createSuccessResult();
    }


    @ApiOperation(value="重新生成二维码")
    @ApiImplicitParam(name = "id", value = "实验id", required = true, dataType = "String",paramType = "path")
    @PostMapping("/qrcode/{id}")
    public  RestResponse<String> regenerateQrcode(HttpServletRequest request,@PathVariable String id) throws Exception{
        return ResponseFactory.createSuccessResult( expirementService.regenerateQrcode(request,id));
    }
    @ApiOperation(value="根据工程标准编号查找")
    @ApiImplicitParam(name = "stdCode", value = "工程标准编号", required = true, dataType = "String",paramType = "path")
    @GetMapping("/stdCode/{stdCode}")
    public RestResponse<Expirement> getByStdCode(@PathVariable String stdCode){
        return ResponseFactory.createSuccessResult(expirementRepository.findByStdCode(stdCode));
    }

}
